#include "my_gtc_dialog.h"

my_gtc_dialog::my_gtc_dialog(QWidget *parent): QDialog(parent)
{
    check_network(false);
    setupUi(this);

#ifdef WINCE
//    HideMzTopBar();
#endif

    /*enable cache*/
    QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
#ifdef WINCE
    QString location = "\\Temp\\cache";
#else
    QString location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
#endif
    //QMessageBox::information(this, "cache", location);
    
    diskCache->setCacheDirectory(location);
    www->page()->networkAccessManager()->setCache(diskCache);

    total_trans = 0;
    this->setWindowTitle("MBrowser v0.2.1e [V2KO]");

    www->load(QUrl("home.htm"));
    www->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
    www->settings()->setAttribute(QWebSettings::ZoomTextOnly, false);
    www->settings()->setMaximumPagesInCache(0);
    www->settings()->setObjectCacheCapacities(0, 0, 0);
    www->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    //www->setTextSizeMultiplier(1);    

    connect(go_btn, SIGNAL(clicked()),this, SLOT(goto_url()));

    connect(www, SIGNAL(loadFinished(bool)), this, SLOT(load_over(bool)));
    connect(www, SIGNAL(loadProgress(int)), this, SLOT(up_progress(int)));
    connect(www, SIGNAL(linkClicked(QUrl)), this, SLOT(up_link(QUrl)));
    connect(www, SIGNAL(urlChanged(QUrl)), this, SLOT(up_link_show(QUrl)));

    connect(kb_btn, SIGNAL(toggled(bool)), this, SLOT(mb_showkb(bool)));

    //my_gtc_dialog::grabMouse();
    www->installEventFilter(this);    

    /*read stored cookies to memory*/
    //cookies = new mb_cookies();
    //www->page()->networkAccessManager()->setCookieJar(cookies);

    //set_css_style("user.css");
}

bool my_gtc_dialog::set_css_style(QString css_file)
{
#ifdef WINCE
    www->settings()->setUserStyleSheetUrl(QUrl("file:///disk/programs/mbrowser/"+css_file));
#else
    www->settings()->setUserStyleSheetUrl(QUrl("file:///D:/QtWork/study/s3/"+css_file));
#endif
    return true;
}

void my_gtc_dialog::up_link_string(QString url_string)
{
    up_link(QUrl(url_string));
}

void my_gtc_dialog::up_link(QUrl link)
{
    /*popup a beautiul dialog to confirm link?*/
#if 0
    int ret = QMessageBox::warning(this, QString(),
                           tr("Open this link? link:").append(link.toString()),
                           QMessageBox::Yes | QMessageBox::No,
                           QMessageBox::No);
    if (ret == QMessageBox::No)
            return;
#endif
    www->load(link);    
    up_link_show(link);
}

void my_gtc_dialog::up_link_show(QUrl link)
{
    url_line->setText(link.toString());
}

void my_gtc_dialog::mb_showkb(bool show)
{
#ifdef WINCE
    if(show)
    {
        //SipShowIM(SIPF_ON);
        MzOpenSip(IM_SIP_MODE_GEL_PY, 0);
    }
    else
    {
        MzCloseSip();
    }    
#endif
}

void my_gtc_dialog::mousePressEvent(QMouseEvent *event)
{
    if(Qt::LeftButton == event->button())
    {
        //QMessageBox::information(this, "msg", "press left button!");
    }    
}

bool my_gtc_dialog::eventFilter(QObject *target, QEvent *event)
{
    if(target == www)
    {
        if(event->type() == QEvent::InputMethod)
        {
            //QMessageBox::information(this, "input", "haha");
        }

        if(event->type() == QEvent::MouseButtonDblClick)
        {
            QMouseEvent *mEvent = static_cast<QMouseEvent *>(event);
            if(mEvent->pos().y() < 100)
            {
                if(mEvent->pos().x() < 240)
                {
                    qDebug() << "ready to Quit";
#ifdef WINCE
                    //ShowMzTopBar();
#endif
                    qApp->quit();
                }
                else
                {
                    www->stop();
                }
                return true;
            }
            else
            {
                /*enter zoom mode*/
                in_drag = false;
                in_zoom = true;

                /*some map app needs to continue*/
                if(check_map_url(www->url().toString())) return true;
            }
        }
        if(event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mEvent = static_cast<QMouseEvent *>(event);
            drag_x = mEvent->pos().x();
            drag_y =  mEvent->pos().y();

            click_pt.setX(drag_x);
            click_pt.setY(drag_y);
            in_drag = true;
        }

        if(event->type() == QEvent::MouseButtonRelease)
        {
            /*avoid drag trigger click:)*/
            bool is_move_click = false;
            if(in_drag || in_zoom)
            {
                QMouseEvent *mEvent = static_cast<QMouseEvent *>(event);
                int x_move = mEvent->pos().x()-click_pt.x();
                int y_move = mEvent->pos().y()-click_pt.y();

                if((abs(x_move) > 5) || (abs(y_move) > 5))
                {
                    is_move_click = true;
                }                
            }

            /*clear drag,zoom mode*/
            in_drag = false;
            in_zoom = false;

            if(is_move_click)
            {
                /*ignore click:)*/
                /*some map app needs to continue*/
                if(check_map_url(www->url().toString())) return true;
            }
        }

        if(event->type() == QEvent::MouseMove)
        {
            QMouseEvent *mEvent = static_cast<QMouseEvent *>(event);
            if(in_drag)
            {                
                int fix_x = drag_x-mEvent->pos().x();
                int fix_y = drag_y-mEvent->pos().y();

                www->page()->currentFrame()->scroll(fix_x, fix_y);

                //www->page()->mainFrame()->scroll(fix_x, fix_y);
                //www->page()->mainFrame()->setScrollPosition(mEvent->pos());

                drag_x = mEvent->pos().x();
                drag_y =  mEvent->pos().y();

                /*some map app needs to continue*/
                if(check_map_url(www->url().toString())) return true;
            }
            if(in_zoom)
            {
                if(mEvent->x()-drag_x > 200)
                {
                    www->page()->triggerAction(QWebPage::Forward);
                    in_zoom = false; /*avoid double forward*/                    
                }
                if(mEvent->x()-drag_x < -200)
                {
                    www->page()->triggerAction(QWebPage::Back);
                    in_zoom = false;
                }

                if((mEvent->y()-drag_y) > 50)
                {
                    www->page()->mainFrame()->setZoomFactor(1.5);
                }
                if((mEvent->y()-drag_y) > 250)
                {
                    www->page()->mainFrame()->setZoomFactor(2.0);
                }
                if((mEvent->y()-drag_y) < -50)
                {
                    www->page()->mainFrame()->setZoomFactor(1.0);
                }
                if((mEvent->y()-drag_y) < -250)
                {
                    www->page()->mainFrame()->setZoomFactor(0.8);
                }
                return true;
            }
        }

    }

    return QDialog::eventFilter(target, event);
}

void my_gtc_dialog::mouseDoubleClickEvent(QMouseEvent *event)
{
    if(Qt::LeftButton == event->button())
    {
        //QMessageBox::information(this, "msg", "dbl press left button!");
    }
}

void my_gtc_dialog::mouseMoveEvent(QMouseEvent *event)
{
    //QMessageBox::information(this, "msg", "move");
    qDebug() << "mouse move event";
}

void my_gtc_dialog::showEvent(QShowEvent *event)
{
    qDebug() << "show event";
}

void my_gtc_dialog::up_progress(int progress)
{
    QString cnt_str;   

    progressBar->setVisible(true);
    progressBar->setValue(progress);
    info_label->setVisible(true);

    /*show network data*/
    quint64 page_cnt = www->page()->bytesReceived()/1024;
    QTextStream(&cnt_str) << "Page: " << page_cnt << "k, Total: " << (total_trans+page_cnt) << "k";

#ifdef WINCE
    /*show memory usage*/
#if 0
    {
        MEMORYSTATUS m8_mem = {0};
        GlobalMemoryStatus(&m8_mem); 
        qDebug() << "Mem total(P,V,P):" << m8_mem.dwTotalPhys << m8_mem.dwTotalVirtual << m8_mem.dwTotalPageFile;
        qDebug() << "Mem free:" << m8_mem.dwAvailPhys << m8_mem.dwAvailVirtual << m8_mem.dwAvailPageFile;
        qDebug() << "Mem usage x%:" << m8_mem.dwMemoryLoad;
    }
#else
    {
        MEMORYSTATUS m8_mem = {0};
        GlobalMemoryStatus(&m8_mem); 
        QTextStream(&cnt_str) << " Mem:" << m8_mem.dwAvailPhys/1024/1024 << "M";
    }
#endif
#endif

    /*output status*/
    info_label->setText(cnt_str);
}

void my_gtc_dialog::goto_url()
{
    QString to_url = url_line->text();
//    QMessageBox::information(this, "haha", to_url);

    if(0 == to_url.right(4).compare(".htm", Qt::CaseInsensitive))
    {
        /*local htm file, not add http://*/
    }
    if(0 != to_url.left(4).compare("http", Qt::CaseInsensitive))
    {
        /*add http://*/
        to_url.prepend("http://");
    }

    www->load(QUrl(to_url));
#ifdef WINCE
    MzCloseSip();
#endif
    kb_btn->setChecked(false);
}

void my_gtc_dialog::inputMethodEvent(QInputMethodEvent *event)
{
    //QMessageBox::information(this, "haha", "haha");
}

void my_gtc_dialog::load_over(bool)
{    
    quint64 page_cnt = www->page()->bytesReceived()/1024;
    total_trans += page_cnt;

    up_link_show(www->page()->mainFrame()->url());

    progressBar->setVisible(false);
    info_label->setVisible(false);

    /*export function to javascript*/
    www->page()->mainFrame()->addToJavaScriptWindowObject("mbrowser", this);

#if 0
    //www->page()->setViewportSize(www->page()->mainFrame()->contentsSize());
    QImage image(www->page()->viewportSize(), QImage::Format_ARGB32);
    QPainter painter(&image);

    www->page()->mainFrame()->render(&painter);
    painter.end();

    //QImage thumbnail = image.scaled(1000, 1000);
    //thumbnail.save("thumbnail.png");
    image.save("cache.png");
#endif

#if 0
    QPainter pweb;
    QPoint dto;
    dto.setX(20);
    dto.setY(20);
    QRectF target(10.0, 20.0, 80.0, 60.0);
    QRectF source(0.0, 0.0, 70.0, 40.0);
    pweb.begin(this);
    pweb.drawPixmap(target, QPixmap("cache.jpg"), source);
    pweb.end();
#endif
}

bool my_gtc_dialog::check_network(bool no_prompt)
{
#ifdef WINCE
    bool ret = false, dial = no_prompt;
    DWORD net_stat = QueryNetWorkStatus();
        
    //MzBeginWaitDlg(this->winId(), NULL, true);   
    if(NETWORK_NONE == net_stat)
    {
        if(!dial)
        {           
            {
                dial = true;
            }
        }
        
        if(dial)
        {
            /*wait dlg*/
            //MzBeginWaitDlg(this->winId(), NULL, true);   
            //QMessageBox::information(this, "Notice", "Ready to Connect GRPS!");
            int dial_ret = Dial_StartGprsConnect2(this->winId(), GPRS_FORCE_APP_TYPE);
            //MzEndWaitDlg();

            if(RESULT_OK == dial_ret)
            {
                
                /*connect successful*/
                if(!no_prompt)
                {

                    //QMessageBox::information(this, "Notice", "GPRS connected!");
                }
                
                /*return successful*/
                ret = true;
            }            
            else
            {
                QMessageBox::information(this, "Error", "GPRS Failed!");
            }
        }        
    }
    else
    {
        /*already connected, but not always have internet connection:)*/
        /***need fix***/
        ret = true;
    }

    return ret;
#else
    return true;
#endif
}

